<template>
    <div>
      <!-- 面包屑导航区 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>学院管理</el-breadcrumb-item>
        <el-breadcrumb-item>班级列表</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 卡片视图区 -->
      <el-card>
        <!-- 搜索与添加区域-->
        <el-row :gutter= "20">
          <el-col :span="4">
            <el-cascader
              placeholder="请选择专业"
              v-model="queryInfo.select"
              :options="majorList"
              :props="{ expandTrigger: 'hover'}"
              clearable
              filterable
              separator="--"
              :show-all-levels="false">
            </el-cascader>
          </el-col>
          <el-col :span="5"> <!---->
            <el-input placeholder="请输入内容" v-model="queryInfo.query" class="input-with-select" clearable @clear="getClassListLimit" >
              <el-button slot="append" icon="el-icon-search" @click="getClassListLimit"></el-button>
            </el-input>
          </el-col>
          <el-col :span="15">
            <el-button type="primary" @click="addClassDialogVisible = true">添加班级</el-button>
          </el-col>
        </el-row>

        <!-- 班级列表主体区域 -->
        <el-table :data="classList" border stripe>
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-table :data="scope.row.studentList"  border >
                <el-table-column align="center" type="index" label="#"></el-table-column>
                <el-table-column align="center" prop="userName" label="学号" sortable></el-table-column>
                <el-table-column align="center" prop="stuName" label="姓名"></el-table-column>
                <el-table-column align="center"  label="性别">
                  <template slot-scope="scope">
                    <div v-if="scope.row.stuGender === 1">
                      <svg class="icon" aria-hidden="true">
                        <use xlink:href="#icon-nan"></use>
                      </svg>
                    </div>
                    <div v-else>
                      <svg class="icon" aria-hidden="true">
                        <use xlink:href="#icon-nv"></use>
                      </svg>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column align="center" prop="stuIndate" label="入住时间"></el-table-column>
                <el-table-column align="center" prop="stuBed" label="床铺号"></el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column align="center" type="index" label="#"></el-table-column>
          <el-table-column align="center" prop="className" label="班级名称" sortable></el-table-column>
          <el-table-column align="center" prop="major.majorName" label="所属专业"></el-table-column>
          <el-table-column align="center" prop="classTeacher" label="辅导员"></el-table-column>
          <el-table-column align="center" label="操作" width="200px">
            <template slot-scope="scope">
              <!-- 修改按钮 -->
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditClassDialog(scope.row)"  ></el-button>
              <!-- 删除按钮 -->
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteClassDialog(scope.row.className)"></el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum"
          :page-sizes="[10, 15, 20]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>

        <!-- 添加班级对话框 -->
        <el-dialog
          title="添加班级"
          :visible.sync="addClassDialogVisible"
          width="50%"
          @close="addClassDialogClosed">
          <el-form :model="addClassForm" :rules="addClassFormRules" ref="addClassFormRef" label-width="100px">
            <el-form-item label="专业名称" prop="major">
              <el-cascader
                placeholder="请选择专业"
                v-model="addClassForm.major"
                :options="majorList_add"
                :props="{ expandTrigger: 'hover'}"
                filterable
                separator="--"
                :show-all-levels="false">
              </el-cascader>
            </el-form-item>
            <el-form-item label="所属年级" prop="level">
              <el-select placeholder="请选择" v-model="addClassForm.level">
                <el-option
                  v-for="item in levelList"
                  :key="item.value"
                  :label="item.label + '级'"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="班级编号" prop="className">
              <el-input v-model="addClassForm.className"/>
            </el-form-item>
            <el-form-item label="辅导员" prop="classTeacher">
              <el-input v-model="addClassForm.classTeacher"/>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addClassDialogVisible = false" >取 消</el-button>
            <el-button type="primary" @click="addClass">确 定</el-button>
          </span>
        </el-dialog>

        <!-- 编辑班级对话框-->
        <el-dialog
          title="编辑班级"
          :visible.sync="editClassDialogVisible"
          width="50%"
          @close="editClassDialogClosed">
          <el-form :model="editClassForm" :rules="addClassFormRules" ref="editClassFormRef" label-width="100px">
            <el-form-item label="专业名称" prop="major">
              <el-cascader
                placeholder="请选择专业"
                v-model="editClassForm.major"
                :options="majorList_edit"
                :props="{ expandTrigger: 'hover'}"
                filterable
                separator="--"
                :show-all-levels="false">
              </el-cascader>
            </el-form-item>
            <el-form-item label="所属年级" prop="level">
              <el-select placeholder="请选择" v-model="editClassForm.level">
                <el-option
                  v-for="item in levelList"
                  :key="item.value"
                  :label="item.label + '级'"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="班级编号" prop="className">
              <el-input v-model="editClassForm.className"/>
            </el-form-item>
            <el-form-item label="辅导员" prop="classTeacher">
              <el-input v-model="editClassForm.classTeacher"/>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editClassDialogVisible = false" >取 消</el-button>
            <el-button type="primary" @click="editClass">确 定</el-button>
          </span>
        </el-dialog>
      </el-card>

    </div>
</template>

<script>
    export default {
        data() {
          return {
            /*获取班级列表的参数对象*/
            queryInfo: {
              select: '',
              query: '',
              //当前的页数
              pageNum: 1,
              //当前每页显示多少条数据
              pageSize: 10
            },
            /* 专业集合 */
            majorList: [],
            majorList_add: [],
            majorList_edit: [],
            /* 年级列表 */
            levelList: [],
            /* 班级列表集合 */
            classList: [],
            /* total总数*/
            total: 0,
            /* 控制添加班级的对话框的显示/隐藏 */
            addClassDialogVisible: false,
            /* 控制修改班级的对话框的显示/隐藏 */
            editClassDialogVisible: false,
            /*添加对话表单数据*/
            addClassForm: {
              major: [],
              level: '',
              className: '',
              classTeacher: ''
            },
            addForm: {
              majorId: '',
              className: '',
              classTeacher: ''
            },
            /* 编辑对话框 */
            editClassForm: {
              major: [],
              classId: '',
              level: '',
              className: '',
              classTeacher: ''
            },
            editForm: {
              classId: '',
              majorId: '',
              className: '',
              classTeacher: ''
            },
            /* 表单验证规则*/
            addClassFormRules: {
              major: [
                {required: true, message: '请选择专业', trigger: 'blur'}
              ],
              level: [
                {required: true, message: '请选择年级', trigger: 'blur'}
              ],
              className: [
                {required: true, message: '请输入班级编号', trigger: 'blur'},
                {
                  pattern: /^\d{1,4}$/,
                  message: '最大长度4位的纯数字'
                }
              ],
              classTeacher: [
                {required: true, message: '请输入辅导员姓名', trigger: 'blur'},
                {
                  pattern: /[\u4e00-\u9fa5]{2,5}$/,
                  message: '输入2-5位字符长度的中文姓名'
                }
              ]
            }
          }
        },

      created() {
          this.getMajorList();
          this.getClassListLimit();
      },

      methods: {
        /* 获取专业列表集合 */
        async getMajorList() {
          const {data: res} = await this.$axios.get(this.$http+'/collegeManageController/getCollegeList');
          let that = this;
          //获取后台数据，重新复制给级联菜单
          res.datas.collegeList.forEach(function (item) {
            let obj = { value: item.collegeId, label: item.collegeName, children: []};
            item.majorList.forEach(function (childrenItem) {
              let childrenObj = { value: childrenItem.majorId, label: childrenItem.majorName};
              obj.children.push(childrenObj);
            })
            that.majorList.push(obj)
          });
          //添加、编辑对话框
          res.datas.collegeList.forEach(function (item) {
            let obj = { value: item.collegeId, label: item.collegeName, children: []};
            item.majorList.forEach(function (childrenItem) {
            let childrenObj = { value: childrenItem.majorId + '&' + childrenItem.majorName, label: childrenItem.majorName};
              obj.children.push(childrenObj);
            })
            that.majorList_add.push(obj);
            that.majorList_edit.push(obj);
          });
          //获取年级列表
          this.$axios.get('./static/json/classLevel.json').then(res => {
            this.levelList = res.data.data;
          })

        },

        /* 获取班级列表集合*/
        async getClassListLimit() {
          console.log(this.queryInfo)
          this.queryInfo.select = (this.queryInfo.select.length === 0) ? '' :this.queryInfo.select[1];
          const {data: res} = await this.$axios.get(this.$http+'/collegeManageController/getClassListLimit',{
            params: this.queryInfo
          });
          this.classList = res.datas.classList;
          this.total = res.datas.total;
        },

        /* 添加班级信息 */
        addClass() {
          this.$refs.addClassFormRef.validate(valid => {
            if (!valid) return;
            //进行数据截取，获取专业id，专业名称
            let str = this.addClassForm.major[1];
            let majorId = str.split("&")[0];
            let majorName = str.split("&")[1];
            this.addForm.majorId = majorId;
            this.addForm.className = majorName + this.addClassForm.level + (parseInt(this.addClassForm.className) <= 9 ? "0"+parseInt(this.addClassForm.className) : this.addClassForm.className) + "班";
            this.addForm.classTeacher = this.addClassForm.classTeacher;
            console.log(this.addForm)
            //表单验证
            this.$refs.addClassFormRef.validate(valid => {
              if (!valid) return;
              //添加之前，判断是否在数据库存在
              this.$axios.get(this.$http+'/collegeManageController/checkClass',{
                params: {
                  majorId: this.addForm.majorId,
                  className: this.addForm.className
                }
              }).then(res => {
                if (res.data.code === 100)
                  return this.$message.warning("该班级已录入")
                //请求
                this.$axios.post(this.$http+'/collegeManageController/addClass', this.addForm).then(res => {
                  if (res.data.code === 200)
                    this.$message.success("添加班级成功！");
                  else if (res.data.code === 100 )
                    this.$message.error("添加班级失败！");
                  //隐藏添加对话框
                  this.addClassDialogVisible = false;
                  //刷新班级列表
                  this.getClassListLimit();
                }).catch(err => {
                  this.$message.error("后台异常，添加失败")
                })
              }).catch(err => {
                this.$message.error("后台异常，班级查重失败")
              })

            })
          })

        },

         /* 显示编辑对话框 */
        showEditClassDialog(row) {
          this.$axios.get(this.$http+'/collegeManageController/getClassInfo',{
            params: {
              majorId: row.major.majorId,
              className: row.className
            }
          }).then(res => {
            //设置级联菜单默认显示
            let arry1 = res.data.datas.classInfo.major.collegeId;
            let arry2 =res.data.datas.classInfo.major.majorId+'&'+res.data.datas.classInfo.major.majorName;
            this.editClassForm.major = [arry1,arry2]
            //设置年级、班级编号、辅导员默认显示
            let str = res.data.datas.classInfo.className;
            let start = res.data.datas.classInfo.major.majorName.length;
            let end = str.length
            let level_number = str.substring(start,end - 1);
            let level = level_number.substring(0,2);
            let number = level_number.substring(2);
            this.editClassForm.classId = row.classId;
            this.editClassForm.level = level;
            this.editClassForm.className = number;
            this.editClassForm.classTeacher = res.data.datas.classInfo.classTeacher;
          }).catch(err => {
            this.$message.error("后台异常，数据回显失败")
          });
          //显示对话框
          this.editClassDialogVisible = true;
        },

        /* 提交修改 */
        editClass() {
          this.$refs.editClassFormRef.validate(valid => {
            if (!valid) return;
            let str = this.editClassForm.major[1];
            let majorId = str.split("&")[0];
            let className = str.split("&")[1] + this.editClassForm.level + (parseInt(this.editClassForm.className) <= 9 ? "0"+parseInt(this.editClassForm.className) : this.editClassForm.className) + "班";
            this.editForm.classId = this.editClassForm.classId;
            this.editForm.majorId = majorId;
            this.editForm.className = className;
            this.editForm.classTeacher = this.editClassForm.classTeacher;

            this.$axios.put(this.$http+'/collegeManageController/editClass', this.editForm).then(res => {
              if (res.data.code === 100)
                this.$message.warning("修改班级信息失败");
              else if (res.data.code === 200)
                this.$message.success("修改班级信息成功");
              else if (res.data.code === 300)
                this.$message.warning("该班级信息已经录入");
              //隐藏对话框
              this.editClassDialogVisible = false;
              //刷新列表
              this.getClassListLimit();
            }).catch(err => {
              this.$message.error("后台异常，更新数据失败")
            })
          })
        },

        /* 删除班级信息 */
        async deleteClassDialog(className) {
          //弹框是否确认删除
          const confirmResult = await this.$confirm('此操作将删除该班级所有信息, 是否继续?', '提示', {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning'
          }).catch(err => err);
          if(confirmResult !== 'confirm')
            return this.$message.info('已取消删除');
          //发送删除请求
          this.$axios.delete(this.$http+'/collegeManageController/deleteClass?className='+className).then(res => {
            if (res.data.code === 200)
              this.$message.success("该班级及其相关信息已删除.");
            else if (res.data.code === 100)
              this.$message.warning("后台处理异常，删除失败");
            this.getClassListLimit();
          }).catch(err => err)
        },

        /* 监听 pageSize 改变的事件 */
        handleSizeChange(newSize) {
          this.queryInfo.pageSize = newSize;
          //每次改变之后，重新获取数据
          this.getClassListLimit();
        },

        /* 监听 pageNum 改变的事件 */
        handleCurrentChange(newPage) {
          this.queryInfo.pageNum = newPage ;
          //每次改变之后，重新获取数据
          this.getClassListLimit();
        },

        /* 监听添加对话框的关闭， 对其进行清空 */
        addClassDialogClosed() {
          this.$refs.addClassFormRef.resetFields();
        },

        /* 监听编辑对话框的关闭， 对其进行清空 */
        editClassDialogClosed() {
          this.$refs.editClassFormRef.resetFields();
        },
      }
    }
</script>

<style scoped lang="less">

</style>
